//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.eResearch.Publisher.Wcf
{
    using System;
    using Microsoft.Research.eResearch.Blackboard.Common;
    using Microsoft.Research.eResearch.Publisher.Interfaces;
    using Microsoft.Research.eResearch.Publisher.Wcf.WcfPublisherMessageService;

    /// <summary>
    /// Provides a WCF implementation of the IPublisherMessageSender interface.
    /// This implementation allows the publisher to register and unregister with the blackboard,
    /// as well as to publish new messages to the blackboard.
    /// </summary>
    public class WcfPublisherMessageClient : IPublisherMessageSender
    {
        /// <summary>
        /// Registers the specified return address (location of the IPublisherSubscriptionReceiver) with
        /// the blackboard, and obtains the intial subscription profile.
        /// </summary>
        /// <param name="returnAddress">The return address of the publisher.</param>
        /// <returns>The initial subscription profile for the publisher.</returns>
        public SubscriptionProfile Register(Uri returnAddress)
        {
            SubscriptionProfile profile = null;

            WcfPublisherMessageServiceClient client = new WcfPublisherMessageServiceClient("WcfPublisherMessageClient");
            client.Open();
            profile = new SubscriptionProfile(client.Register(returnAddress));
            client.Close();

            return profile;
        } 

        /// <summary>
        /// Unregisters the specified return address of the publisher from the blackboard.
        /// </summary>
        /// <param name="returnAddress">The return address of the publisher.</param>
        public void Unregister(Uri returnAddress)
        {
            WcfPublisherMessageServiceClient client = new WcfPublisherMessageServiceClient("WcfPublisherMessageClient");
            client.Open();
            client.Unregister(returnAddress);
            client.Close();
        } 

        /// <summary>
        /// Publishes the specified message to the blackboard.
        /// </summary>
        /// <param name="message">The blackboard message.</param>
        public void Publish(BlackboardMessage message)
        {
            WcfPublisherMessageServiceClient client = new WcfPublisherMessageServiceClient("WcfPublisherMessageClient");
            client.Open();
            client.Publish(message);
            client.Close();
        } 
    }
}
